import router from '@/router/index'
import { addUserRouter } from '@/utils'

router.beforeEach(async (to, from) => {
  if (to.path === '/login') {
    return
  }

  const KEY = 'userStorage'
  let userData: any = window.sessionStorage.getItem(KEY) || ''
  userData = userData ? JSON.parse(userData) : null
  const token: string = userData?.token

  if (!token) {
    return '/login'
  }

  if (from.matched.length === 0) {
    addUserRouter(userData?.menu)

    if (!to.redirectedFrom) {
      return to.fullPath
    }

    return
  }

  return
})
